package no.saiboten.tourbuilder.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import no.saiboten.tourbuilder.login.AuthorizationLevel;
import no.saiboten.tourbuilder.user.User;
import no.saiboten.tourbuilder.user.UserStatusImpl;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class SecurityInterceptor extends HandlerInterceptorAdapter implements
		HandlerInterceptor {

	final Logger LOGGER = Logger.getLogger(getClass());

	@Autowired
	UserStatusImpl userStatus;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse arg1, Object arg2) throws Exception {
		LOGGER.debug("In prehandle!");
		Object userObj = request.getSession().getAttribute("user");
		if (userObj != null) {
			User user = (User) userObj;
			if (user.getAuthLevel().equals(AuthorizationLevel.USER)
					|| user.getAuthLevel().equals(AuthorizationLevel.ADMIN)) {
				userStatus.setAuthenticated(true);
				userStatus.setAuthenticatedUser(user);
				LOGGER.debug("User is authenticated!");
			} else {
				LOGGER.debug("User is not authenticated ..");
				userStatus.setAuthenticated(false);
			}
		}
		return true;
	}
}
